﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VodafoneWP7.Resources;
using System.IO;
using System.Windows.Threading;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Text;
using Microsoft.Phone.Tasks;

namespace VodafoneWP7
{
    public enum MessaggingServiceType
    {
        Wp7 = 0,
        VodafoneItalia = 1,
        Giovani = 2,
        TIM = 3,
        TinIt = 4
        //None
    }

    public static class MessaggingServices
    {
        public static List<AMessageService> AvailableServices;// = new List<AMessageService>();
        public static void LoadAvailableServices()
        {
            AvailableServices = new List<AMessageService>(5){null,null,null,null, null};
            var a = (int)MessaggingServiceType.Giovani;
            AvailableServices[a] = new Giovani();
            AvailableServices[(int)MessaggingServiceType.VodafoneItalia] = new VodafoneItalia();
            AvailableServices[(int)MessaggingServiceType.Wp7] = new Wp7();
            AvailableServices[(int)MessaggingServiceType.TIM] = new TelecomItaliaMobile();
            AvailableServices[(int)MessaggingServiceType.TinIt] = new TinIt();
        }
        public static AMessageService GetService(MessaggingServiceType type)
        {
            return AvailableServices[(int)type];
        }
    }

    public abstract class AMessageService
    {
        //public string name;
        //public Uri imageUri;
        //protected string username;
        //protected string password;
        public CookieContainer cookieJar;
        //protected Action<BitmapImage> onVerificationCodeRequired;
        //protected Action<string> onError;
        //protected Action onTaskCompleted;

        //protected Dispatcher Dispatcher;
        //protected NavigationService NavigationService;
        protected ConnectionQueue connections;

        public MessaggingServiceType type;
        //public MessageService(string username, string password, Action<BitmapImage> onVerificationCodeRequired, Action<string> onError, Action onTaskCompleted, Dispatcher dispatcher, NavigationService NavigationService)
        //{
        //    this.username = username;
        //    this.password = password;
        //    this.onVerificationCodeRequired = onVerificationCodeRequired;
        //    this.onTaskCompleted = onTaskCompleted;
        //    this.onError = onError;
        //    this.Dispatcher = dispatcher;
        //    this.NavigationService = NavigationService;
        //    this.cookieJar = new CookieContainer();
        //}

        public AMessageService(MessaggingServiceType type)
        {
            this.cookieJar = new CookieContainer();
            this.type = type;
        }

        //public abstract void SendMessage(string number, string message);

        public abstract void SubmitVerificationCode(string code, Image image, MainPageStatus status, Action<string> onError, Action onTaskCompleted, Dispatcher Dispatcher);

        public abstract void SendSMS(Account account, MainPageStatus status, Action<BitmapImage> onVerificationCodeRequired, Action<string> onError, Action<string, string> webBrowserRequired, Action onTaskCompleted, Dispatcher Dispatcher);

        public abstract int GetRemainingAvailableSMS(Account account);

        public abstract int GetRemainingAvailableMMS(Account account);

        public virtual bool UsernamePassowrdRequired()
        {
            return false;
        }

        public virtual bool AllowCheckUserPasswordCorrectness() { return false; }

        public virtual void CheckUserPasswordCorrectness(Account account, Action<string> onError, Action onTaskCompleted, Dispatcher Dispatcher) { }

        public virtual void Stop()
        {
            if (connections != null)
                connections.Stop();
        }
        public virtual string GetName()
        {
            return "Unknown";
        }
        public virtual string GetDescription()
        {
            return "no description";
        }
        public virtual Uri GetImageUri()
        {
            return new Uri(" ", UriKind.RelativeOrAbsolute);
        }
    }
    
    public class VodafoneItalia : AMessageService
    {
        public static readonly string name = "Vodafone Italia";
        public static readonly Uri imageUri = new Uri("\\Images\\vodafone.png", UriKind.RelativeOrAbsolute);

        public VodafoneItalia()
            : base(MessaggingServiceType.VodafoneItalia)
        {
            //name = "Vodafone Italia";
            //imageUri = new Uri("\\Images\\vodafone.png", UriKind.RelativeOrAbsolute);
        }
        
        public override void SubmitVerificationCode(string code, Image image, MainPageStatus status, Action<string> onError, Action onTaskCompleted, Dispatcher Dispatcher)
        {
            string number = status.number;
            string message = status.message;
            Connection.connectHTMLwithGet("http://www.areaprivati.vodafone.it/190/fsms/send.do?receiverNumber=" + HttpUtility.UrlEncode(number) + "&message=" + HttpUtility.UrlEncode(message) + "&verifyCode=" + HttpUtility.UrlEncode(code), cookieJar,
            (response) =>
            {
                //if (stopped)
                //    return;
                var sr = new StreamReader(response.GetResponseStream());
                var html = sr.ReadToEnd();
                if (!html.Contains("correttamente"))
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        onError(Strings.WrongVerificationCode);
                    });
                    Connection.connectHTMLwithGet(
                        "http://www.areaprivati.vodafone.it/190/fsms/generateimg.do",
                        cookieJar,
                        (resp) =>
                        {
                            //if (stopped)
                            //    return;
                            Dispatcher.BeginInvoke(() =>
                            {
                                try
                                {
                                    var bi = new System.Windows.Media.Imaging.BitmapImage();
                                    bi.SetSource(resp.GetResponseStream());
                                    image.Source = bi;
                                    //Image.Source = bi;
                                    //Image.Visibility = System.Windows.Visibility.Visible;
                                    response.Close();
                                    //sendbutton.IsEnabled = true;
                                }
                                catch (Exception ex)
                                {
                                    ex.ToString();
                                    Dispatcher.BeginInvoke(() =>
                                    {
                                        //onError("Errore nell'inserimento del codice di verifica");
                                        onError(Strings.WrongVerificationCode);
                                    });
                                }
                            });
                        },
                        () =>
                        {
                            //if (stopped)
                            //    return;
                            Dispatcher.BeginInvoke(() =>
                            {
                                onError(Strings.ConnectionError);
                            });
                        }
                    );
                }
                else
                {
                    //if (stopped)
                    //    return;
                    Dispatcher.BeginInvoke(() =>
                    {
                        onError(Strings.MessageSentSuccessfully);
                        onTaskCompleted();
                        //NavigationService.GoBack();
                    });
                }
                //Image.Visibility = System.Windows.Visibility.Collapsed;
            }, () => { });
        }
        
        public override void SendSMS(Account account, MainPageStatus status, Action<BitmapImage> onVerificationCodeRequired, Action<string> onError, Action<string, string> webBrowserRequired, Action onTaskCompleted, Dispatcher Dispatcher)
        {
            string number = status.number;
            string message = status.message;
            connections = new ConnectionQueue();
            connections.AddConnection(new ConnectionGET()
            {

                url = "https://www.vodafone.it/190/trilogy/jsp/login.do?username=" + HttpUtility.UrlEncode(account.Username) + "&password=" + HttpUtility.UrlEncode(account.Password),
                CookieContainer = cookieJar,
                prevProcessor = (_) => { },
                currProcessor = (_) => { },
                onError = () =>
                {
                    onError(Strings.ConnectionError);
                }
            });

            connections.AddConnection(new ConnectionGET()
            {
                url = "http://www.areaprivati.vodafone.it/190/trilogy/jsp/dispatcher.do?ty_key=fsms_hp&ipage=next",
                CookieContainer = cookieJar,
                prevProcessor = (_) => { },
                currProcessor = (response) =>
                {
                    var sr = new StreamReader(response.GetResponseStream());
                    if (!sr.ReadToEnd().Contains("Ciao"))
                        Dispatcher.BeginInvoke(() =>
                        {
                            onError(Strings.LoginError_CheckUserPassword);
                            connections.Stop();
                        });
                },
                onError = () =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        onError(Strings.ConnectionError);
                    });
                }
            });
            connections.AddConnection(new ConnectionGET()
            {
                url = "http://www.areaprivati.vodafone.it/190/trilogy/jsp/dispatcher.do?ty_key=fsms_hp&ipage=next",
                CookieContainer = cookieJar,
                prevProcessor = (_) => { },
                currProcessor = (_) => { },
                onError = () =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        onError(Strings.ConnectionError);
                    });
                }
            });
            connections.AddConnection(new ConnectionGET()
            {
                url = "http://www.areaprivati.vodafone.it/190/fsms/prepare.do?receiverNumber=" + HttpUtility.UrlEncode(number) + "&message=" + HttpUtility.UrlEncode(message),
                CookieContainer = cookieJar,
                prevProcessor = (_) => { },
                currProcessor = (response) =>
                {
                    var sr = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    if (!sr.Contains("Ciao"))
                        connections.currentConnection = 0;
                    if (sr.Contains("solo a numeri di cellulare Vodafone") || sr.Contains("Il numero di telefono del destinatario del messaggio non"))
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            onError(Strings.VodafoneNumberError);
                        });
                        connections.Stop();
                        onTaskCompleted();
                        return;
                    }
                    if (sr.Contains("correttamente"))
                    {
                        connections.Stop();
                        Dispatcher.BeginInvoke(() =>
                        {
                            onError(Strings.MessageSentSuccessfully);
                        });
                        onTaskCompleted();
                        return;
                    }
                },
                onError = () =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        onError(Strings.ConnectionErrorSendindMessage);
                    });
                }
            });
            connections.AddConnection(new ConnectionGET()
            {
                url = "http://www.areaprivati.vodafone.it/190/fsms/generateimg.do",
                CookieContainer = cookieJar,
                prevProcessor = (_) => { },
                currProcessor = (response) =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        try
                        {
                            var bi = new System.Windows.Media.Imaging.BitmapImage();
                            bi.SetSource(response.GetResponseStream());
                            onVerificationCodeRequired(bi);
                            response.Close();
                        }
                        catch (Exception)
                        {
                            onError(Strings.ConnectionError);
                            connections.Stop();
                            onTaskCompleted();
                            return;
                        }
                    });
                },
                onError = () =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        onError(Strings.ConnectionError);
                    });
                }
            });

            connections.Run();

            //return connections;

        }

        public override int GetRemainingAvailableSMS(Account account)
        {
            int available = 10;
            DateTime now = DateTime.Now;
            for (int i = 0; i < account.messages.Count; i++)
            {
                var m = account.messages[i];
                if (m.dateTime.Date.Equals(now.Date))
                    available--;
            }

            return available;
        }

        public override int GetRemainingAvailableMMS(Account account)
        {
            return 0;
        }
        
        public override string GetName()
        {
            return name;
        }
        
        public override string GetDescription()
        {
            return "bla\ndsafjdslkfs\ndssfsdòflkdjsfdkfjdsjfljdsjkfdfjldskfjdslfkjdslfjdkòjjfkdkòfsjfkdsfdskfdsòljòkjsfòsfòskjfsòlkfjsòkjdkjdsòadòk";
        }
       
        public override Uri GetImageUri()
        {
            return imageUri;
        }

        public override bool AllowCheckUserPasswordCorrectness()
        {
            return true;
        }

        public override void CheckUserPasswordCorrectness(Account account, Action<string> onError, Action onTaskCompleted, Dispatcher Dispatcher)
        {
            connections = new ConnectionQueue();
            connections.AddConnection(new ConnectionGET()
            {

                url = "https://www.vodafone.it/190/trilogy/jsp/login.do?username=" + HttpUtility.UrlEncode(account.Username) + "&password=" + HttpUtility.UrlEncode(account.Password),
                CookieContainer = cookieJar,
                prevProcessor = (_) => { },
                currProcessor = (_) => { },
                onError = () =>
                {
                    onError(Strings.ConnectionError);
                }
            });

            connections.AddConnection(new ConnectionGET()
            {
                url = "http://www.areaprivati.vodafone.it/190/trilogy/jsp/dispatcher.do?ty_key=fsms_hp&ipage=next",
                CookieContainer = cookieJar,
                prevProcessor = (_) => { },
                currProcessor = (response) =>
                {
                    var sr = new StreamReader(response.GetResponseStream());
                    if (!sr.ReadToEnd().Contains("Ciao"))
                        Dispatcher.BeginInvoke(() =>
                        {
                            onError(Strings.LoginError_CheckUserPassword);
                            connections.Stop();
                        });
                    else
                        Dispatcher.BeginInvoke(() =>
                        {
                            onTaskCompleted();
                        });
                },
                onError = () =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        onError(Strings.ConnectionError);
                    });
                }
            });

            connections.Run();
        }

        public override bool UsernamePassowrdRequired()
        {
            return true;
        }
    }
    
    public class Giovani : AMessageService
    {

        public Giovani()
            : base(MessaggingServiceType.Giovani)
        {
        }


        StringBuilder numberName, messageName;
        public override void SendSMS(Account account, MainPageStatus status, Action<BitmapImage> onVerificationCodeRequired, Action<string> onError, Action<string, string> webBrowserRequired, Action onTaskCompleted, Dispatcher Dispatcher)
        {
            numberName = new StringBuilder();
            messageName = new StringBuilder();

            connectionQueue = new ConnectionQueue();

            connectionQueue.AddConnection(
                new ConnectionPOST()
                {
                    url = "http://my.giovani.it/all/login.php?nick=" + account.Username + "&password=" + account.Password,
                    CookieContainer = cookieJar,
                    prevProcessor = (_) => { },
                    currProcessor = (resp) => { },
                    onError = () => { }
                });

            connectionQueue.AddConnection(
                new ConnectionPOST()
                {
                    url = "http://freesms.giovani.it",
                    CookieContainer = cookieJar,
                    prevProcessor = (_) => { },
                    currProcessor = (response) =>
                    {

                        var html = new StreamReader(response.GetResponseStream()).ReadToEnd();
                        var str = "Numero: <input type=\"text\" name=\"";
                        var startindex = html.IndexOf(str) + str.Length; ;
                        var endindex = html.IndexOf('"', startindex);
                        numberName.Append(html.Substring(startindex, endindex - startindex));

                        html = html.Insert(html.IndexOf("value=\"", endindex) + 7, status.number);

                        str = "messaggio: <textarea name=\"";
                        startindex = html.IndexOf(str) + str.Length;
                        endindex = html.IndexOf('"', startindex);
                        messageName.Append(html.Substring(startindex, endindex - startindex));

                        html = html.Insert(html.IndexOf(">", endindex) + 1, status.message);

                        var head = html.IndexOf("</head>");

                        html = html.Replace("\"/", "\"http://freesms.giovani.it/");
                        MainPage.cookieJar = cookieJar;

                        Dispatcher.BeginInvoke(() =>
                        {
                            webBrowserRequired(html, "http://freesms.giovani.it/");
                        });

                    },
                    onError = () => { }
                });

            connectionQueue.Run();
            //Connection.connectHTMLwithPost("http://my.giovani.it/all/login.php","nick=lcosmo&password=aezahb6v", cookieJar,
            //    (response) => {

            //        var html = new StreamReader(response.GetResponseStream()).ReadToEnd();
            //        html=html;
            //        Connection.connectHTMLwithGet("http://freesms.giovani.it", cookieJar,
            //        (response2) =>
            //        {
            //            var html2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();
            //            var str = "Numero: <input type=\"text\" name=\"";
            //            var startindex = html2.IndexOf(str) + str.Length; ;
            //            var endindex = html2.IndexOf('"', startindex);
            //            var numberName = html2.Substring(startindex, endindex - startindex);

            //            str = "messaggio: <textarea name=\"";
            //            startindex = html2.IndexOf(str) + str.Length;
            //            endindex = html2.IndexOf('"', startindex);
            //            var messageName = html2.Substring(startindex, endindex - startindex);



            //            html = html;
            //        }, () =>
            //        {


            //        });
            //    }, () => {


            //    });

        }

        public override int GetRemainingAvailableMMS(Account account)
        {
            return 10;// throw new NotImplementedException();
        }


        public override int GetRemainingAvailableSMS(Account account)
        {
            return 10;//throw new NotImplementedException();
        }


        public override void SubmitVerificationCode(string code, Image image, MainPageStatus status, Action<string> onError, Action onTaskCompleted, Dispatcher Dispatcher)
        {
            //throw new NotImplementedException();
        }

        public override string GetName()
        {
            return "Giovani";
        }

        ConnectionQueue connectionQueue;
        public override void Stop()
        {
            if (connectionQueue != null)
                connectionQueue.Stop();
        }

        public override bool UsernamePassowrdRequired()
        {
            return true;
        }
    }

    public class TelecomItaliaMobile : AMessageService
    {

        public TelecomItaliaMobile()
            : base(MessaggingServiceType.TIM)
        {
        }
        
        StringBuilder UrlConstructor, messageName;
        public override void SendSMS(Account account, MainPageStatus status, Action<BitmapImage> onVerificationCodeRequired, Action<string> onError, Action<string, string> webBrowserRequired, Action onTaskCompleted, Dispatcher Dispatcher)
        {
            UrlConstructor = new StringBuilder();
            messageName = new StringBuilder();

            connectionQueue = new ConnectionQueue();

            connectionQueue.AddConnection(
                new ConnectionPOST()
                {
                    url = "https://www.tim.it/authfe/login.do?login=" + account.Username + "&password=" + account.Password,
                    //url = "https://www.tim.it/authfe/login.do?login=3331011827&password=11235813&portale=timPortale&urlOk=https%3A%2F%2Fwww.119selfservice.tim.it%2F119%2Fconsumerdispatcher",
                    CookieContainer = cookieJar,
                    prevProcessor = (_) => { },
                    currProcessor = (response) =>
                    {
                        var html = new StreamReader(response.GetResponseStream()).ReadToEnd();
                        html = html;
                    },
                    onError = () => { }
                });
            connectionQueue.AddConnection(
                new ConnectionPOST()
                {
                    url = "https://smsweb.tim.it/sms-web/adddispatch?start=new",
                    CookieContainer = cookieJar,
                    prevProcessor = (_) => { },
                    currProcessor = (response) =>
                    {
                        
                        var html = new StreamReader(response.GetResponseStream()).ReadToEnd();
                        var str = "input name=\"t:formdata\" type=\"hidden\" value=\"";
                        var startindex = html.IndexOf(str) + str.Length; ;
                        var endindex = html.IndexOf('"', startindex);
                        var con_url = "https://smsweb.tim.it/sms-web/adddispatch.adddispatchform?";
                        con_url += "t%3Aformdata=" + HttpUtility.UrlEncode(html.Substring(startindex, endindex - startindex));

                        str = "input id=\"seperateFreeNumbers:hidden\" name=\"t:formdata\" type=\"hidden\" value=\"";
                        startindex = html.IndexOf(str, endindex) + str.Length; ;
                        endindex = html.IndexOf('"', startindex);
                        con_url += "&t%3Aformdata=" + HttpUtility.UrlEncode(html.Substring(startindex, endindex - startindex));
                                               
                        
                        con_url += "&recipientType=FREE_NUMBERS";
                        con_url += "&freeNumbers="+HttpUtility.UrlEncode(status.number);
                        con_url += "&contactListId=";
                        con_url += "&contactsIdString=";
                        con_url += "&deliverySmsClass=STANDARD";
                        con_url += "&textAreaStandard="+HttpUtility.UrlEncode(status.message);
                        con_url += "&textAreaFlash=";
                        con_url += "&modelsSelect=";
                        UrlConstructor.Append(con_url);
                       
                    },
                    onError = () => { }
                });
                connectionQueue.AddConnection(
                new ConnectionPOST()
                {
                    later_url = UrlConstructor,                    
                    CookieContainer = cookieJar,
                    prevProcessor = (_) => { },
                    currProcessor = (response) =>
                    {
                        var html = new StreamReader(response.GetResponseStream()).ReadToEnd();
                        var str = "input name=\"t:formdata\" type=\"hidden\" value=\"";
                        var startindex = html.IndexOf(str) + str.Length; ;
                        var endindex = html.IndexOf('"', startindex);                        
                        var con_url = "https://smsweb.tim.it/sms-web/adddispatch.adddispatchform?";
                        tformdata = "t%3Aformdata=" + HttpUtility.UrlEncode(html.Substring(startindex, endindex - startindex));
                    },
                    onError = () => { }
                });
                connectionQueue.AddConnection(
                new ConnectionGET()
                {
                    url = "https://smsweb.tim.it/sms-web/validatecaptcha:image/false?" + HttpUtility.UrlEncode("t:ac") + "=Dispatch",                    
                    CookieContainer = cookieJar,
                    prevProcessor = (_) => { },
                    currProcessor = (response) =>
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            var bi = new System.Windows.Media.Imaging.BitmapImage();
                            bi.SetSource(response.GetResponseStream());
                            onVerificationCodeRequired(bi);
                            response.Close();
                        });
                    },
                    onError = () => { }
                });
            connectionQueue.Run();
      

        }
        String tformdata = "";

        public override int GetRemainingAvailableMMS(Account account)
        {
            return 10;// throw new NotImplementedException();
        }


        public override int GetRemainingAvailableSMS(Account account)
        {
            return 10;//throw new NotImplementedException();
        }


        public override void SubmitVerificationCode(string code, Image image, MainPageStatus status, Action<string> onError, Action onTaskCompleted, Dispatcher Dispatcher)
        {
            var param = "t%3Aac=Dispatch&"+ tformdata + "&verificationCode=" + HttpUtility.UrlEncode(code);
            Connection.connectHTMLwithPost("https://smsweb.tim.it/sms-web/validatecaptcha.validatecaptchaform", param, cookieJar,
            (response) =>
            {                
                var sr = new StreamReader(response.GetResponseStream());
                var html = sr.ReadToEnd();
                html = html;
                //INVIO RIUSCITO: sms inviato
                //NUMERO NON TIM: SMS non inviato, il numero non è TIM


                //if (!html.Contains("correttamente"))
                //{
                //    Dispatcher.BeginInvoke(() =>
                //    {
                //        onError(Strings.WrongVerificationCode);
                //    });
                //    Connection.connectHTMLwithGet(
                //        "http://www.areaprivati.vodafone.it/190/fsms/generateimg.do",
                //        cookieJar,
                //        (resp) =>
                //        {
                //            //if (stopped)
                //            //    return;
                //            Dispatcher.BeginInvoke(() =>
                //            {
                //                try
                //                {
                //                    var bi = new System.Windows.Media.Imaging.BitmapImage();
                //                    bi.SetSource(resp.GetResponseStream());
                //                    image.Source = bi;
                //                    //Image.Source = bi;
                //                    //Image.Visibility = System.Windows.Visibility.Visible;
                //                    response.Close();
                //                    //sendbutton.IsEnabled = true;
                //                }
                //                catch (Exception ex)
                //                {
                //                    ex.ToString();
                //                    Dispatcher.BeginInvoke(() =>
                //                    {
                //                        //onError("Errore nell'inserimento del codice di verifica");
                //                        onError(Strings.WrongVerificationCode);
                //                    });
                //                }
                //            });
                //        },
                //        () =>
                //        {
                //            //if (stopped)
                //            //    return;
                //            Dispatcher.BeginInvoke(() =>
                //            {
                //                onError(Strings.ConnectionError);
                //            });
                //        }
                //    );
                //}
                //else
                //{
                //    //if (stopped)
                //    //    return;
                //    Dispatcher.BeginInvoke(() =>
                //    {
                //        onError(Strings.MessageSentSuccessfully);
                //        onTaskCompleted();
                //        //NavigationService.GoBack();
                //    });
                //}
                //Image.Visibility = System.Windows.Visibility.Collapsed;
            }, () => { });
        }


        public override string GetName()
        {
            return "Giovani";
        }

        ConnectionQueue connectionQueue;
        public override void Stop()
        {
            if (connectionQueue != null)
                connectionQueue.Stop();
        }

        public override bool UsernamePassowrdRequired()
        {
            return true;
        }
    }

    public class TinIt : AMessageService
    {

        public TinIt()
            : base(MessaggingServiceType.TinIt)
        {
        }

        StringBuilder UrlConstructor, messageName;
        public override void SendSMS(Account account, MainPageStatus status, Action<BitmapImage> onVerificationCodeRequired, Action<string> onError, Action<string, string> webBrowserRequired, Action onTaskCompleted, Dispatcher Dispatcher)
        {
            UrlConstructor = new StringBuilder();
            messageName = new StringBuilder();

            connectionQueue = new ConnectionQueue();

            connectionQueue.AddConnection(
                new ConnectionPOST()
                {
                    url = "https://aaacsc.alice.it/piattaformaAAA/aapm/amI?usernameDisplay=gmrfcb&password=gmrfcb&dominio=%40tin.it&login=gmrfcb%40tin.it&pwd=gmrfcb&channel=Vmail&URL_OK=https%3A%2F%2Fauthsrs.alice.it%2Faap%2Faap_redir.jsp%3Fentry%3DVmail&URL_KO=https%3A%2F%2Fauthsrs.alice.it%2Faap%2Faap_redir_ko.jsp%3Fentry%3DVmail&servizio=mail&msisdn=gmrfcb&username=gmrfcb%40tin.it&user=gmrfcb%40tin.it&a3afep=http%3A%2F%2Fportale.rossoalice.alice.it%2Fps%2FManageCodError.do%3Fcode%3D470%26channel%3DVmail&DOMAIN=tin.it&PASS=gmrfcb&self=true&a3si=none&a3st=VCOMM&totop=true&nototopa3ep=true&a3aid=lvmes&a3flag=0&a3ep=http%3A%2F%2Ffeulogin.alice.it%2Ffeulogin%2Flogin%2FLogin.action&a3epvf=http%3A%2F%2Fwebmailvtin.alice.it%2Fcp%2Fps%2FMain%2Flogin%2FSSOLogin&a3se=http%3A%2F%2Fportale.rossoalice.alice.it%2Fps%2FManageCodError.do%3Fcode%3D470%26channel%3DVmail&a3dcep=http%3A%2F%2Fcommunicator.alice.it%2Fasp%2Fhomepage.asp%3Fs%3D005&a3l=gmrfcb%40tin.it&a3p=gmrfcb",
                    //url = "https://www.tim.it/authfe/login.do?login=3331011827&password=11235813&portale=timPortale&urlOk=https%3A%2F%2Fwww.119selfservice.tim.it%2F119%2Fconsumerdispatcher",
                    CookieContainer = cookieJar,
                    prevProcessor = (_) => { },
                    currProcessor = (response) =>
                    {
                        var html = new StreamReader(response.GetResponseStream()).ReadToEnd();

                        var str = "href=\"";
                        var startindex = html.IndexOf(str) + str.Length; ;
                        var endindex = html.IndexOf('"', startindex);
                        var con_url = HttpUtility.UrlDecode(html.Substring(startindex, endindex - startindex));

                        UrlConstructor.Append(con_url);
                    },
                    onError = () => {
                        var s = "ciao";
                    }
                });

            connectionQueue.AddConnection(
            new ConnectionGET()
            {
                url = "http://webmailvtin.alice.it/POST%20/cp/ps/main/SPMobileCommands/SPSendSMS?d=tin.it&u=gmrfcb&t=22d512350d18d112d98d&l=it%20sms_to_recipients=3491580861&mobileTextInfo=Per%20inserire%20pi%C3%B9%20numeri%20telefonici%20separarli%20da%20una%20virgola%20o%20da%20un%20punto%20e%20virgola.&mobiletext=2Teast2&mobileTextCounter=Caratteri%20utilizzati%204%2F145",
                CookieContainer = cookieJar,
                prevProcessor = (_) => { },
                currProcessor = (response) =>
                {
                    var html = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    html = html;
                },
                onError = () => { }
            });
            //connectionQueue.AddConnection(
            //    new ConnectionPOST()
            //    {
            //        url = "https://smsweb.tim.it/sms-web/adddispatch?start=new",
            //        CookieContainer = cookieJar,
            //        prevProcessor = (_) => { },
            //        currProcessor = (response) =>
            //        {

            //            var html = new StreamReader(response.GetResponseStream()).ReadToEnd();
            //            var str = "input name=\"t:formdata\" type=\"hidden\" value=\"";
            //            var startindex = html.IndexOf(str) + str.Length; ;
            //            var endindex = html.IndexOf('"', startindex);
            //            var con_url = "https://smsweb.tim.it/sms-web/adddispatch.adddispatchform?";
            //            con_url += "t%3Aformdata=" + HttpUtility.UrlEncode(html.Substring(startindex, endindex - startindex));

            //            str = "input id=\"seperateFreeNumbers:hidden\" name=\"t:formdata\" type=\"hidden\" value=\"";
            //            startindex = html.IndexOf(str, endindex) + str.Length; ;
            //            endindex = html.IndexOf('"', startindex);
            //            con_url += "&t%3Aformdata=" + HttpUtility.UrlEncode(html.Substring(startindex, endindex - startindex));


            //            con_url += "&recipientType=FREE_NUMBERS";
            //            con_url += "&freeNumbers=" + HttpUtility.UrlEncode(status.number);
            //            con_url += "&contactListId=";
            //            con_url += "&contactsIdString=";
            //            con_url += "&deliverySmsClass=STANDARD";
            //            con_url += "&textAreaStandard=" + HttpUtility.UrlEncode(status.message);
            //            con_url += "&textAreaFlash=";
            //            con_url += "&modelsSelect=";
            //            UrlConstructor.Append(con_url);

            //        },
            //        onError = () => { }
            //    });
            //connectionQueue.AddConnection(
            //new ConnectionPOST()
            //{
            //    later_url = UrlConstructor,
            //    CookieContainer = cookieJar,
            //    prevProcessor = (_) => { },
            //    currProcessor = (response) =>
            //    {
            //        var html = new StreamReader(response.GetResponseStream()).ReadToEnd();
            //        var str = "input name=\"t:formdata\" type=\"hidden\" value=\"";
            //        var startindex = html.IndexOf(str) + str.Length; ;
            //        var endindex = html.IndexOf('"', startindex);
            //        var con_url = "https://smsweb.tim.it/sms-web/adddispatch.adddispatchform?";
            //        tformdata = "t%3Aformdata=" + HttpUtility.UrlEncode(html.Substring(startindex, endindex - startindex));
            //    },
            //    onError = () => { }
            //});
            //connectionQueue.AddConnection(
            //new ConnectionGET()
            //{
            //    url = "https://smsweb.tim.it/sms-web/validatecaptcha:image/false?" + HttpUtility.UrlEncode("t:ac") + "=Dispatch",
            //    CookieContainer = cookieJar,
            //    prevProcessor = (_) => { },
            //    currProcessor = (response) =>
            //    {
            //        Dispatcher.BeginInvoke(() =>
            //        {
            //            var bi = new System.Windows.Media.Imaging.BitmapImage();
            //            bi.SetSource(response.GetResponseStream());
            //            onVerificationCodeRequired(bi);
            //            response.Close();
            //        });
            //    },
            //    onError = () => { }
            //});
            connectionQueue.Run();


        }
        String tformdata = "";

        public override int GetRemainingAvailableMMS(Account account)
        {
            return 10;// throw new NotImplementedException();
        }


        public override int GetRemainingAvailableSMS(Account account)
        {
            return 10;//throw new NotImplementedException();
        }


        public override void SubmitVerificationCode(string code, Image image, MainPageStatus status, Action<string> onError, Action onTaskCompleted, Dispatcher Dispatcher)
        {
            var param = "t%3Aac=Dispatch&" + tformdata + "&verificationCode=" + HttpUtility.UrlEncode(code);
            Connection.connectHTMLwithPost("https://smsweb.tim.it/sms-web/validatecaptcha.validatecaptchaform", param, cookieJar,
            (response) =>
            {
                var sr = new StreamReader(response.GetResponseStream());
                var html = sr.ReadToEnd();
                html = html;
                //INVIO RIUSCITO: sms inviato
                //NUMERO NON TIM: SMS non inviato, il numero non è TIM


                //if (!html.Contains("correttamente"))
                //{
                //    Dispatcher.BeginInvoke(() =>
                //    {
                //        onError(Strings.WrongVerificationCode);
                //    });
                //    Connection.connectHTMLwithGet(
                //        "http://www.areaprivati.vodafone.it/190/fsms/generateimg.do",
                //        cookieJar,
                //        (resp) =>
                //        {
                //            //if (stopped)
                //            //    return;
                //            Dispatcher.BeginInvoke(() =>
                //            {
                //                try
                //                {
                //                    var bi = new System.Windows.Media.Imaging.BitmapImage();
                //                    bi.SetSource(resp.GetResponseStream());
                //                    image.Source = bi;
                //                    //Image.Source = bi;
                //                    //Image.Visibility = System.Windows.Visibility.Visible;
                //                    response.Close();
                //                    //sendbutton.IsEnabled = true;
                //                }
                //                catch (Exception ex)
                //                {
                //                    ex.ToString();
                //                    Dispatcher.BeginInvoke(() =>
                //                    {
                //                        //onError("Errore nell'inserimento del codice di verifica");
                //                        onError(Strings.WrongVerificationCode);
                //                    });
                //                }
                //            });
                //        },
                //        () =>
                //        {
                //            //if (stopped)
                //            //    return;
                //            Dispatcher.BeginInvoke(() =>
                //            {
                //                onError(Strings.ConnectionError);
                //            });
                //        }
                //    );
                //}
                //else
                //{
                //    //if (stopped)
                //    //    return;
                //    Dispatcher.BeginInvoke(() =>
                //    {
                //        onError(Strings.MessageSentSuccessfully);
                //        onTaskCompleted();
                //        //NavigationService.GoBack();
                //    });
                //}
                //Image.Visibility = System.Windows.Visibility.Collapsed;
            }, () => { });
        }


        public override string GetName()
        {
            return "Tin";
        }

        ConnectionQueue connectionQueue;
        public override void Stop()
        {
            if (connectionQueue != null)
                connectionQueue.Stop();
        }

        public override bool UsernamePassowrdRequired()
        {
            return true;
        }
    }

    public class Wp7 : AMessageService
    {
        public static string name = "Windows Phone 7";
        public static Uri imageUri = new Uri("/Images/wp7.png", UriKind.RelativeOrAbsolute);
        public Wp7()
            : base(MessaggingServiceType.Wp7)
        {
        }
        public override void SendSMS(Account account, MainPageStatus status, Action<BitmapImage> onVerificationCodeRequired, Action<string> onError, Action<string, string> webBrowserRequired, Action onTaskCompleted, Dispatcher Dispatcher)
        {
            SmsComposeTask sms = new SmsComposeTask();
            sms.To = status.number;
            sms.Body = status.message;
            sms.Show();
        }

        public override int GetRemainingAvailableMMS(Account account)
        {
            return 0;
        }


        public override int GetRemainingAvailableSMS(Account account)
        {
            return int.MaxValue;
        }


        public override void SubmitVerificationCode(string code, Image image, MainPageStatus status, Action<string> onError, Action onTaskCompleted, Dispatcher Dispatcher)
        {

        }

        public override string GetName()
        {
            return name;
        }

        public override void Stop()
        {
        }

        public override string GetDescription()
        {
            return "bla\ndsafjdslkfs\ndssfsdòflkdjsfdkfjdsjfljdsjkfdfjldskfjdslfkjdslfjdkòjjfkdkòfsjfkdsfdskfdsòljòkjsfòsfòskjfsòlkfjsòkjdkjdsòadòk";
        }
        public override Uri GetImageUri()
        {
            return imageUri;
        }

    }
}
